package org.usmile.algorithms.learn.graph.dfs;

import org.usmile.algorithms.learn.graph.AdjList;
import org.usmile.algorithms.learn.graph.Graph;

public class ConnectedComponent {
    /**
     * 深度优先遍历 递归
     */
    public int count(Graph graph) {
        if (graph == null) {
            return 0;
        }

        int count = 0;
        boolean[] visited = new boolean[graph.getV()];
        for (int v = 0; v < graph.getV(); v++) {
            if (!visited[v]) {
                count++;
                dfs(graph, v, visited);
            }
        }

        return count;
    }

    private void dfs(Graph graph, int v, boolean[] visited) {
        visited[v] = true;
        for (int w : graph.adj(v)) {
            if (!visited[w]) {
                dfs(graph, w, visited);
            }
        }
    }

    public static void main(String[] args) {
        Graph graph = new AdjList(3);
        graph.addEdge(0, 1);
        graph.addEdge(0, 2);

        System.out.println(new ConnectedComponent().count(graph));
    }
}
